﻿using DAL;
using IBLL;
using IDAL;
using Models;
using Models.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BLL
{
    public class RoleInfoBLL: IRoleInfoBLL
    {
        private IRoleInfoDAL _roleInfoDAL;//角色表数据访问
        private UnmanContexts _dbContext;//数据上下文
        private IEmployee_RoleInfoDAL _employee_RoleInfoDAL;//用户角色表数据访问
        private IR_RoleInfo_MenuInfoDAL _r_RoleInfo_MenuInfoDAL;//菜单权限角色表数据访问
        public RoleInfoBLL(
            IRoleInfoDAL roleInfoDAL
            , UnmanContexts dbContext
            , IEmployee_RoleInfoDAL employee_RoleInfoDAL
            , IR_RoleInfo_MenuInfoDAL r_RoleInfo_MenuInfoDAL
            )
        {
            _roleInfoDAL = roleInfoDAL;
            _dbContext = dbContext;
            _employee_RoleInfoDAL = employee_RoleInfoDAL;
            _r_RoleInfo_MenuInfoDAL = r_RoleInfo_MenuInfoDAL;
        }



        #region 查询角色列表的方法（GetRoleInfos）


        /// <summary>
        /// 查询角色列表的方法
        /// </summary>
        /// <param name="page">第一页</param>
        /// <param name="limit">每页几条数据</param>
        /// <param name="roleName">用户姓名</param>
        /// <param name="count">数据总量</param>
        /// <returns></returns>
        public List<GetRoleInfoDTO> GetRoleInfos(int page, int limit, string roleName, out int count)
        {


            #region 新的方法
            //linq方法进行链表
            var data = from r in _dbContext.RoleInfo.Where(r => r.IsDalete == false)
                       select new GetRoleInfoDTO
                       {
                           Id = r.Id,
                           RoleName = r.RoleName,
                           Description = r.Description,
                           CreateTime = r.CreateTime
                       };

            //角色姓名不为空
            if (!string.IsNullOrWhiteSpace(roleName))
            {
                data = data.Where(r => r.RoleName.Contains(roleName));
            }

            //求总数
            count = data.Count();
            //分页
            var listPage = data.OrderByDescending(u => u.CreateTime).Skip(limit * (page - 1)).Take(limit).ToList();
            //返回结果
            return listPage;



            #endregion

        }

        #endregion


        #region 添加用户的方法（GetRoleInfo）
        /// <summary>
        /// 添加用户的方法
        /// </summary>
        /// <param name="entity">新用户的实体</param>
        /// <returns></returns>
        public bool CreateRoleInfo(RoleInfo entity, out string msg)
        {
            //判断这个用户非空信息
            if (string.IsNullOrWhiteSpace(entity.RoleName))
            {
                msg = "角色姓名不能为空！";
                return false;
            }

            //判断账号是否重复
            RoleInfo role = _roleInfoDAL.GetEntities().FirstOrDefault(u => u.RoleName == entity.RoleName);
            if (role != null)
            {
                msg = "角色名已经存在！";
                return false;
            }
            //赋值id
            entity.Id = Guid.NewGuid().ToString();
            //时间
            entity.CreateTime = DateTime.Now;
            //加密密码
            //entity.PassWord = MD5Helper.GenerateMD5(entity.PassWord);
            //更新到数据库
            bool isSuccess = _roleInfoDAL.CreateEntity(entity);
            //判断是否成功
            /*if (isSuccess)
            {
                msg = $"添加{entity.UserName}成功！";
            }
            else
            {
                msg = "添加用户失败!";
            }*/

            msg = isSuccess ? $"添加{entity.RoleName}成功!" : "添加用户失败!";
            return isSuccess;

        }



        #endregion

        #region 用户软删除方法（DeleteRoleInfo）
        /// <summary>
        /// 用户软删除方法
        /// </summary>
        /// <param name="id">要删除的用户id</param>
        /// <returns></returns>
        public bool DeleteRoleInfo(string id)
        {
            //根据id查用户是否存在
            RoleInfo role = _roleInfoDAL.GetEntityById(id);
            if (role == null)
            {
                return false;
            }
            //修改用户的状态
            role.IsDalete = true;
            role.DeleteTime = DateTime.Now;
            //返回结果
            return _roleInfoDAL.UpdateEntity(role);

        }
        #endregion

        #region 批量软用户软删除方法(DeleteRoleInfo)

        /// <summary>
        /// 批量软用户软删除方法
        /// </summary>
        /// <param name="ids">被删除的用户id集合</param>
        /// <returns></returns>
        public bool DeleteRoleInfo(List<string> ids)
        {
            // var userList = _userInfoDAL.GetUserInfos().Where(u => ids.Contains(u.Id)).ToList();
            foreach (var id in ids)
            {
                //根据用户id查询用户
                //UserInfo userInfo = userList.FirstOrDefault(u => u.Id == id);
                RoleInfo role = _roleInfoDAL.GetEntityById(id);
                if (role == null)
                {
                    continue;//跳出本次循坏
                }
                role.IsDalete = true;
                role.DeleteTime = DateTime.Now;
                //执行修改
                _roleInfoDAL.UpdateEntity(role);
            }

            return true;
        }


        #endregion

        #region 更新用户信息方法（UpdateRoleInfo）

        /// <summary>
        /// 更新用户信息方法
        /// </summary>
        /// <param name="roleInfo">要更新的实体</param>
        /// /// <param name="msg">返回的消息</param>
        /// <returns></returns>
        public bool UpdateRoleInfo(RoleInfo roleInfo, out string msg)
        {
            #region 非空判断


            //页面的非空判断
            if (string.IsNullOrWhiteSpace(roleInfo.Id))
            {
                msg = "id不能为空！";
                return false;
            }
            if (string.IsNullOrWhiteSpace(roleInfo.RoleName))
            {
                msg = "角色姓名不能为空！";
                return false;
            }
            /*if (string.IsNullOrWhiteSpace(userInfo.PassWord))
            {
                msg = "密码不能为空！";
                return false;
            }*/
            #endregion



            //判断这个id是否存在用户
            RoleInfo entity = _roleInfoDAL.GetEntityById(roleInfo.Id);
            if (entity == null)
            {
                msg = "用户id无效";
                return false;
            }

            //先判断是不是跟原来的账号一样，一样表示没有修改
            if (entity.RoleName != roleInfo.RoleName)
            {
                //通过账号查询数据库是否存在相同的账号
                RoleInfo oldUser = _roleInfoDAL.GetEntities().FirstOrDefault(r => r.RoleName == roleInfo.RoleName);
                if (oldUser != null)
                {
                    msg = "用户已被使用";
                    return false;
                }
            }

            //赋值
            entity.RoleName = roleInfo.RoleName;
            entity.RoleName = roleInfo.RoleName;
            //用户密码，如果传进来的是null或""字符串就使用原来的密码，否侧就拿新密码  MD5加密使用密码
            //entity.PassWord = string.IsNullOrWhiteSpace(userInfo.PassWord) ? entity.PassWord : MD5Helper.GenerateMD5(userInfo.PassWord);
            /* entity.PhoneNum = userInfo.PhoneNum;
             entity.Email = userInfo.Email;
             entity.DepartmentId = userInfo.DepartmentId;
             entity.Sex = userInfo.Sex;*/
            entity.RoleName = roleInfo.RoleName;
            entity.Description = roleInfo.Description;
            //更新到库
            bool isOK = _roleInfoDAL.UpdateEntity(entity);
            msg = isOK ? "修改用户成功" : "修改用户失败";
            //返回结果
            return isOK;
        }

        #endregion



        #region 获取角色已经绑定的用户id集（GetBindUserIds）


        /// <summary>
        /// 获取已经绑定的用户id集
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        public List<string> GetBindUserIds(string roleId)
        {
            //查询当前角色已经绑定的用户的id
            List<string> userIds = _employee_RoleInfoDAL.GetEntities()
                                                          .Where(x => x.RoleId == roleId)
                                                          .Select(x => x.StaffId)
                                                          .ToList();
            return userIds;
        }


        #endregion

        #region 获取角色已经绑定的菜单id集（GetBindMenuIds）


        /// <summary>
        /// 获取已经绑定的菜单id集
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        public List<string> GetBindMenuIds(string roleId)
        {
            //查询当前角色已经绑定的用户的id
            List<string> menuIds = _r_RoleInfo_MenuInfoDAL.GetEntities()
                                                          .Where(x => x.RoleId == roleId)
                                                          .Select(x => x.MenuId)
                                                          .ToList();
            return menuIds;
        }


        #endregion

        #region 绑定用户角色的方法（BindStaffInfo）


        /// <summary>
        /// 绑定用户角色的方法
        /// </summary>
        /// <param name="userIds"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public bool BindStaffInfo(List<string> userIds, string roleId)
        {
            //当前角色已经绑定的用户列表
            List<Employee_RoleInfo> BinUserList = _employee_RoleInfoDAL.GetEntities().Where(x => x.RoleId == roleId).ToList();

            #region 解绑

            foreach (var item in BinUserList)
            {
                //查询当前的用户id是否有从前端传过来
                //bool isHas = userIds.Any(u => u == item.UserId);
                bool isHas = userIds == null ? false : userIds.Any(u => u == item.StaffId);
                if (!isHas)
                {
                    //调用删除
                    _employee_RoleInfoDAL.DeleteEntity(item);
                }

            }

            #endregion


            #region 绑定
            if (userIds == null)
            {
                return true;
            }

            foreach (var userId in userIds)
            {
                //var user = BinUserList.FirstOrDefault(x => x.UserId == userId);
                //在序列中查找是否存在该用户id
                bool isHas = BinUserList.Any(x => x.StaffId == userId);
                if (!isHas)
                {
                    //创建一条数据
                    Employee_RoleInfo entity = new Employee_RoleInfo()
                    {
                        Id = Guid.NewGuid().ToString(),
                        StaffId = userId,
                        RoleId = roleId,
                        CreateTime = DateTime.Now
                    };
                    _employee_RoleInfoDAL.CreateEntity(entity);
                }
            }


            #endregion



            return true;
        }
        #endregion

        #region 绑定菜单角色的方法（BindMenuInfo）


        /// <summary>
        /// 绑定菜单角色的方法
        /// </summary>
        /// <param name="menuIds"></param>
        /// <param name="roleId"></param>
        /// <returns></returns>
        public bool BindMenuInfo(List<string> menuIds, string roleId)
        {
            //当前角色已经绑定的用户列表
            List<R_RoleInfo_MenuInfo> BinUserList = _r_RoleInfo_MenuInfoDAL.GetEntities().Where(x => x.RoleId == roleId).ToList();

            #region 解绑

            foreach (var item in BinUserList)
            {
                //查询当前的用户id是否有从前端传过来
                //bool isHas = userIds.Any(u => u == item.UserId);
                bool isHas = menuIds == null ? false : menuIds.Any(u => u == item.MenuId);
                if (!isHas)
                {
                    //调用删除
                    _r_RoleInfo_MenuInfoDAL.DeleteEntity(item);
                }

            }

            #endregion


            #region 绑定
            if (menuIds == null)
            {
                return true;
            }

            foreach (var menuId in menuIds)
            {
                //var user = BinUserList.FirstOrDefault(x => x.UserId == userId);
                //在序列中查找是否存在该用户id
                bool isHas = BinUserList.Any(x => x.MenuId == menuId);
                if (!isHas)
                {
                    //创建一条数据
                    R_RoleInfo_MenuInfo entity = new R_RoleInfo_MenuInfo()
                    {
                        Id = Guid.NewGuid().ToString(),
                        MenuId = menuId,
                        RoleId = roleId,
                        CreateTime = DateTime.Now
                    };
                    _r_RoleInfo_MenuInfoDAL.CreateEntity(entity);
                }
            }


            #endregion



            return true;
        }

       
        #endregion


    }
}
